package bat.iog.hytool.ftp.demo2;

import iog.hytool.ftp.demo1.CreateException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FTPUtil {
    
    //定义一个客户端
    private static FTPClient ftpClient ;

    
    
    

    
    
    

    /**
     * 从FTP服务器上下载文件
     * @param remote 远程文件路径
     * @param local 本地文件路径
     * @return 是否成功
     * @throws IOException
     */
    public boolean download(String remote,String local) throws Exception{
        
        FTPFile[] files = ftpClient.listFiles(remote);
        
        if(files == null || files.length < 0){
            throw new CreateException(-1,"远程文件不存在");
        }
        if(files.length != 1){
            throw new CreateException(-1,"远程文件不唯一");
        }
        File localFile = new File(local);
        if(localFile.exists()){
            long localBeginSize = localFile.length();
            if(localBeginSize == files[0].getSize()){
                throw new CreateException(-1,"文件已经存在");
            }else if(localBeginSize > files[0].getSize()){
                throw new CreateException(-1,"下载文件出错");
            }
            return downloadByUnit(remote,local,localBeginSize,files[0].getSize());
        }else {
            return downloadByUnit(remote,local,0,files[0].getSize());
        }
    }
    
    /**
     * 断点续传下载
     * @param remote
     * @param local
     * @param beginSize
     * @param endSize
     * @return
     * @throws Exception
     */
    private Boolean downloadByUnit(String remote,String local,long beginSize,long endSize) throws Exception {
        File localFile = new File(local);
        long waitSize = endSize - beginSize;
        //进行断点续传，并记录状态
        FileOutputStream out = new FileOutputStream(localFile,true);
        //把文件指针移动到 开始位置
        ftpClient.setRestartOffset(beginSize);
        InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));
        byte[] bytes = new byte[1024];
        int c;
        double finishSize =0;
        double finishPercent = 0;
        while((c = in.read(bytes))!= -1){
            out.write(bytes,0,c);
            finishSize += c;
            /*if(finishSize > waitSize){
                //System.out.println(">>>>>完成进度:" + 1);
                fileObserverAble.setKeyValue(localFile.getName(),1,"download");

            }
            if ((finishSize / waitSize) - finishPercent > 0.01) {
                finishPercent = finishSize / waitSize;
                //System.out.println(">>>>>完成进度:" + finishPercent);
                fileObserverAble.setKeyValue(localFile.getName(),finishPercent,"download");
            }*/
        }
        in.close();
        out.close();
        return ftpClient.completePendingCommand();
    }

}